layui.define(['jquery','layer'], function(exports) {
    "use strict";

    var $ = layui.jquery, layer = layui.layer;

    var defaults = {
        url : undefined,
        param : undefined,
        type : "post",
        dataType : "json",
        contentType : 'application/json',
        success : undefined,
        fail:undefined,
        always:undefined //不管返回结果是成功还是失败，都会执行的方法，服务器异常则不会执行
    };


    var NewAjax = {
        post: function(url,data,success,fail,always) {
            $.post(url,data,function (result) {
                if(always)always();
                if(result.code==0){
                    if(success){
                        success(result.data)
                    }else{
                        layer.msg(result.message||result.msg||"操作成功！")
                    }
                }else{
                    var msg = result.message||result.msg||"操作失败！";
                    if(fail){
                        fail(msg);
                    }else{
                        layer.confirm(msg);
                    }
                }
            },'json')
        },
        postJson: function(options) {
            options=$.extend({}, defaults, options);
            // window.setTimeout(function() {
                $.ajax({
                    url : options.url,
                    data : JSON.stringify(options.param),
                    type : options.type,
                    dataType : options.dataType,
                    contentType : options.contentType,
                    success : function(result) {
                        if(options.always)options.always();
                        if(result.code==0){
                            if(options.success){
                                options.success(result.data)
                            }else{
                                layer.msg(result.message||"操作成功！")
                            }
                        }else{
                            if(options.fail){
                                options.fail(result.message||"操作失败！");
                            }else{
                                layer.alert(result.message||"操作失败！");
                            }
                        }
                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {

                    },
                    beforeSend : function() {

                    },
                    complete : function() {

                    }
                });
            // }, 500);
        }
    };

    exports('newAjax', NewAjax);
});